import * as RongIMLib from '@rongcloud/imlib-v4'

import sha1 from 'js-sha1';
import axios from 'axios'
const qs = require("qs");

export default {
  methods: {
    // 获取 IMLib 实例
    imInit() {
      this.im = RongIMLib.init({ appkey: this.appKey });
    },
    // 获取token
    getToken() {
      return new Promise(res => {
        const Timestamp = new Date().getTime();
        const Nonce = Math.random();
        axios({
          method: "post",
          url: "/rongyun/user/getToken.json",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Signature: sha1(this.appSecret + Nonce + Timestamp),
            "App-Key": this.appKey,
            Timestamp,
            Nonce,
          },
          data: qs.stringify(this.userInfo),
        }).then(({data}) => {
          res([null,data]);
        }).catch(e => {
          res([e])
        })
      })
    },
    // 监听 IMLib 连接状态变化
    watch() {
      this.im.watch({
        // IM 连接状态变更通知
        status(status) {
          console.log(status);
        }
      })
    },
    // 建立 IM 连接
    async linkIM() {
      try {
        const user = await this.im.connect({ token: this.token })
        return Promise.resolve([null, user])
      } catch (error) {
        console.log('链接失败: ', error.code, error.msg);
        return Promise.resolve([error])
      }
    }
  }
}

